#!/usr/bin/python3

import pymysql

# 1. 查询：
# 使用 execute()  方法执行 SQL 查询
# cursor.execute("select * from user_inf")
# 使用 fetchone() 方法获取单条数据.
# data = cursor.fetchall()
# print(data)

# 2. 插入：
def myInsert(word_name, rt_word, unit, bookname):
   # 打开数据库连接
   db = pymysql.connect("localhost", "root", "root", "mywords")

   # 使用 cursor() 方法创建一个游标对象 cursor
   cursor = db.cursor()
   try:
      #插入：
      # sql = "insert into word(words, chinese) values('test', '测试')"
      # sql = "INSERT INTO `mywords`.`word`(`name`, `mean`, `voice_en`, `voice_am`,`unit`,`bookname`) VALUES ('" + word_name + "' , '"+word_mean+"', NULL, NULL, "+ str(unit) +", '恋恋有词');"
      sql = "INSERT INTO `mywords`.`word`(`name`, `mean`, `sentence`, `yinbiao`, `voice_en`, `voice_am`,`unit`,`bookname`) VALUES ('" + word_name + "' , '" + rt_word[0] + "' , '"+ rt_word[1].replace("'", '#') + "'" + ', "' + rt_word[2] + '", NULL, NULL, '+ str(unit) +", '" + bookname + "');"
      # print(sql)
      cursor.execute(sql)
      # 提交到数据库执行
      db.commit()
   except BaseException:
      # 如果发生错误则回滚
      print('----数据库--faile!', word_name, rt_word)
      db.rollback()

   # 关闭数据库连接
   db.close()